import db, {userLoginStatus} from '../../database/lowDB/connectDb.js';
import { randomToken,unioformDateTransform,autoIncreamentKey} from '../../utils/index.js';


class userLoginStatusModel {
    constructor() {
        this.tableName = 'userLoginStatus';
    }
    

    // 获取用户登录状态
    async getUserLoginStatus(token) {
        let currentTime = unioformDateTransform(new Date())
        const user = userLoginStatus.find(item => item.token === token  && 
                                              (new Date(currentTime).getTime() < new Date(item.expiredTime).getTime()) 
                                      );
        if (user) {
            return user;
        }
        return null;
    }


    // 添加新的用户状态
    async addUserLoginStatus(param) {
        let userData = {}
        let date = unioformDateTransform(new Date())
        let token = randomToken()

        userData.id = autoIncreamentKey(userLoginStatus),
        userData.expiredTime = unioformDateTransform(new Date(date).getTime() + 20*60*1000)
        userData.token = token
        userData.loginTime = date
        userData.username = param.userName
        userData.userId = param.id

        userLoginStatus.unshift(userData)
        db.write();
        return {token,loginDate: date};
    }


    // 更新用户登录状态
    async updateUserLoginStatus(token, statusData) {
        const index = userLoginStatus.findIndex(item => item.token === token);
        if (index !== -1) {
            userLoginStatus[index] = {...userLoginStatus[index], ...statusData};
            db.write();
            return true;
        }
        return null;
    }   
}   

export default new userLoginStatusModel();